import React, { useMemo } from "react";
import { useAppDispatch, useAppSelector } from "../../app/hooks";
import { NavLink } from "react-router-dom";
import {
  addCarCount,
  deleteCar,
  subCarCount,
  switchCarCheck,
} from "../../app/module/car/carSlice";
import "./style.scss";

const Index = () => {
  const car = useAppSelector((state) => state.car.car);
  const dispatch = useAppDispatch();
  const totalPrice = useMemo(() => {
    return car.reduce((p, n) => {
      return n.isChecked ? p + n.price * n.count : p;
    }, 0);
  }, [car]);
  if (car.length === 0) {
    return (
      <div>
        <h1>购物没哟商品</h1>
        <NavLink to="/">去买东西把</NavLink>
      </div>
    );
  }

  return (
    <div>
      <div>
        {car.map((v) => {
          return (
            <div key={v.id} className="car-item">
              <input
                type="checkbox"
                checked={v.isChecked}
                onChange={() => dispatch(switchCarCheck(v))}
              />
              <dl>
                <dt>
                  <img src={v.url} alt="" />
                </dt>
                <dd>
                  <h3>{v.title}</h3>
                  <div>单价：{v.price}</div>
                  <div>
                    <button
                      onClick={() => {
                        if (v.count <= 1) {
                          if (window.confirm("在减少就要删除了！！"))
                            dispatch(deleteCar(v));
                        } else {
                          dispatch(subCarCount(v));
                        }
                      }}
                    >
                      -
                    </button>
                    <span>{v.count}</span>
                    <button onClick={() => dispatch(addCarCount(v))}>+</button>
                  </div>
                </dd>
              </dl>
            </div>
          );
        })}
      </div>
      <div>
        <h1>总价： {totalPrice}</h1>
      </div>
    </div>
  );
};

export default Index;
